package com.yncmcc.Service;

import com.yncmcc.Entity.*;
import com.yncmcc.Repository.Interface.ContractsRepository;
import com.yncmcc.Repository.Interface.PeriodRepository;
import com.yncmcc.Repository.Interface.UserRepository;
import com.yncmcc.Service.Interface.ContractsService;
import com.yncmcc.Service.Interface.DepartmentService;
import com.yncmcc.Service.Interface.PeriodService;
import com.yncmcc.Service.Interface.UserService;
import com.yncmcc.Util.STATUS;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Random;

/**
 * Created by CMCC-sunmo on 2016/9/18.
 */
@Service("contractsService")
@Transactional
public class ContractsServiceImpl implements ContractsService {
    private  Map<String , Object> response;

    @Autowired
    private PeriodRepository periodRepository;

    @Autowired
    private ContractsRepository contractsRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PeriodService payLogService;

    @Override
    public ContractsEntity findByContractID(String contractId) {

        return contractsRepository.findByContractID(contractId);
    }

    @Override
    public ContractsEntity findByContractSerial(String contractSerial) {
        return contractsRepository.findByContractSerial(contractSerial);
    }

    @Override
    public String addContract(ContractsEntity contractsEntity) {
        String message = "ok";
        ContractsEntity check = contractsRepository.findByContractSerial(contractsEntity.getContractSerial());
        if(StringUtils.isBlank(contractsEntity.getContractSerial())){
            message =  "合同编号不为空";
            return message;
        }else if(check != null){
            message =  "合同编号已存在";
            return message;
        }else if(StringUtils.isBlank(contractsEntity.getContractName())){
            message =  "合同名称不为空";
            return message;
        }else if(StringUtils.isBlank(contractsEntity.getUserId())){
            message =  "合同提交人ID不为空";
            return message;
        }else if(StringUtils.isBlank(contractsEntity.getDeptId())){
            message =  "提交者部门不为空";
            return message;
        }else if(contractsEntity.getContractCate() == 0){
            message =  "合同类别不为空";
            return message;
        }
        String cate = contractsEntity.getContractCate() + "";
//        System.out.print(cate);
        if(cate.equals("1")) {
            if (contractsEntity.getSrStartTime() == null) {
                message =  "呈批件开始时间不为空";
                return message;
            } else if (contractsEntity.getSrEndTime() == null) {
                message =  "呈批件结束时间不为空";
                return message;
            } else if(contractsEntity.getSrStartTime().getTime() > contractsEntity.getSrEndTime().getTime()){
                message =  "呈批件开始时间不能大于结束时间";
                return message;
            } else if(contractsEntity.getSrIsWarn() == 1){
                if(contractsEntity.getSrRemindTime() == null){
                    message =  "合同呈批件提醒时间不为空编号不为空";
                    return message;
                } else if(contractsEntity.getSrStartTime().getTime() > contractsEntity.getSrRemindTime().getTime()){
                    message =  "呈批件提醒时间不能小于开始时间";
                    return message;
                } else if(contractsEntity.getSrRemindTime().getTime() > contractsEntity.getSrEndTime().getTime()){
                    message =  "呈批件提醒时间不能大于结束时间";
                    return message;
                }
            }
        }else if(cate.equals("2")){
            if(contractsEntity.getEaStartTime() == null) {
                message =  "审批表开始时间不为空";
                return message;
            } else if(contractsEntity.getEaEndTime() == null) {
                message =  "审批表结束时间不为空";
                return message;
            } else if(contractsEntity.getEaStartTime().getTime() > contractsEntity.getEaEndTime().getTime()){
                message =  "审批表开始时间不能大于结束时间";
                return message;
            }else if(contractsEntity.getEaIsWarn() == 1){
                if(contractsEntity.getEaRemindTime() == null){
                    message =  "审批表提醒时间不为空";
                    return message;
                } else if(contractsEntity.getEaStartTime().getTime() > contractsEntity.getEaRemindTime().getTime()){
                    message =  "审批表提醒时间时间不能小于开始时间";
                    return message;
                } else if(contractsEntity.getEaRemindTime().getTime() > contractsEntity.getEaEndTime().getTime()){
                    message =  "合同编号呈批件提醒时间不能大于结束时间不为空";
                    return message;
                }
            }
        }else if(cate.equals("3")){
            if (contractsEntity.getCtStartTime() == null) {
                message =  "合同开始时间不为空";
                return message;
            } else if (contractsEntity.getCtEndTime() == null) {
                message =  "合同结束时间不为空";
                return message;
            } else if(contractsEntity.getCtStartTime().getTime() > contractsEntity.getCtEndTime().getTime()){
                message =  "合同开始时间不能大于结束时间";
                return message;
            } else if(contractsEntity.getCtIsWarn() == 1){
                if(contractsEntity.getCtRemindTime() == null){
                    message =  "合同提醒时间不为空";
                    return message;
                } else if(contractsEntity.getCtStartTime().getTime() > contractsEntity.getCtRemindTime().getTime()){
                    message =  "合同提醒时间时间不能小于开始时间";
                    return message;
                } else if(contractsEntity.getCtRemindTime().getTime() > contractsEntity.getCtEndTime().getTime()){
                    message =  "合同提醒时间不能大于结束时间";
                    return message;
                }
            }else if(StringUtils.isBlank(contractsEntity.getCtPeriodNum() + "")){
                message =  "合同分期次数不为空";
                return message;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        int random = (int)(Math.random()*10000);
        contractsEntity.setContractId(sdf.format(new java.util.Date()) + random + "");
        contractsEntity.setContractStatus(Short.parseShort("1"));
        contractsEntity.setContractCTime(new Timestamp(System.currentTimeMillis()));
        contractsRepository.save(contractsEntity);
        if(contractsEntity.getContractCate() == 3){
            contractsEntity.setCtPeriodNum(contractsEntity.getCtPeriodNum() <= 0 ? 0 : contractsEntity.getCtPeriodNum());
            System.out.println(contractsEntity.getCtPeriodNum());
            for (int i = 0 ; i < contractsEntity.getCtPeriodNum() ; i++){
                PeriodEntity periodEntity = new PeriodEntity();
                periodEntity.setContractId(contractsEntity.getContractId());
                periodEntity.setPeriodCTime(new Timestamp(System.currentTimeMillis()));
                periodEntity.setPeriodStatus((short)1);
                periodEntity.setPeriodId(sdf.format(new java.util.Date()) + (int)(Math.random()*10000) + "");
                periodRepository.save(periodEntity);
            }
        }
        return message;
    }


    @Override
    public List<ContractsCustomEntity> findReqContract(ContractsEntity contractsEntity) {

        if(contractsEntity.getUserId() != null && contractsEntity.getUserId() != ""){

        }

        List<ContractsCustomEntity> contractsEntities = contractsRepository.findReqContract(contractsEntity);

        return  contractsEntities;
    }

    @Override
    public String deleteContract(String contractId) {
        String message = "ok";
        ContractsEntity contractsEntity = contractsRepository.findByContractID(contractId);
        contractsEntity.setContractStatus((short) 0);
        contractsEntity.setContractDTime(new Timestamp(System.currentTimeMillis()));
        contractsRepository.saveAndFlush(contractsEntity);
        return message;
    }

    @Override
    public int updateContract(ContractsEntity contractsEntity) {
        int status = STATUS.SUCCESS;

        if (StringUtils.isBlank(contractsEntity.getContractId())) {
            status = STATUS.ID_EMPTY;
            return status;
        } else {
            String cate = contractsEntity.getContractCate() + "";

            if(cate.equals("1")) {

                /*当需要提醒时，如果提醒时间小于开始时间，或提醒时间大于结束时间，或提醒时间不存在，则ERROR*/
                if(contractsEntity.getSrIsWarn()==1){
                    if(contractsEntity.getSrRemindTime().getTime() < contractsEntity.getSrStartTime().getTime()
                            || contractsEntity.getSrRemindTime().getTime() > contractsEntity.getSrEndTime().getTime()
                            || contractsEntity.getSrRemindTime()==null){
                        status = STATUS.REMINDTIMEERROR;
                        return status;
                    }
                }
//                /*当不需要提醒时，如果提醒时间存在，则ERROR*/
//                else if (contractsEntity.getSrIsWarn()==0 && contractsEntity.getSrRemindTime()!=null){
//                    status = STATUS.REMINDTIMEERROR;
//                    return status;
//                }
                /*如果开始时间大于结束时间，则ERROR*/
                if(contractsEntity.getSrStartTime().getTime() > contractsEntity.getSrEndTime().getTime()){
                    status = STATUS.STARTTIMEERROR;
                    return status;
                }
            }
            else if(cate.equals("2")) {
                /*当需要提醒时，如果提醒时间小于开始时间，或提醒时间大于结束时间，或提醒时间不存在，则ERROR*/
                if(contractsEntity.getEaIsWarn()==1){
                    if(contractsEntity.getEaRemindTime().getTime() < contractsEntity.getEaStartTime().getTime()
                            || contractsEntity.getEaRemindTime().getTime() > contractsEntity.getEaEndTime().getTime()
                            || contractsEntity.getEaRemindTime()==null){
                        status = STATUS.REMINDTIMEERROR;
                        return status;
                    }
                }
//                /*当不需要提醒时，如果提醒时间存在，则ERROR*/
//                else if (contractsEntity.getEaIsWarn()==0 && contractsEntity.getEaRemindTime()!=null){
//                    status = STATUS.REMINDTIMEERROR;
//                    return status;
//                }
                /*如果开始时间大于结束时间，则ERROR*/
                if(contractsEntity.getEaStartTime().getTime() > contractsEntity.getEaEndTime().getTime()){
                    status = STATUS.STARTTIMEERROR;
                    return status;
                }
            }
            else if(cate.equals("3")) {
                                /*当需要提醒时，如果提醒时间小于开始时间，或提醒时间大于结束时间，或提醒时间不存在，则ERROR*/
                if(contractsEntity.getCtIsWarn()==1){
                    if(contractsEntity.getCtRemindTime().getTime() < contractsEntity.getCtStartTime().getTime()
                            || contractsEntity.getCtRemindTime().getTime() > contractsEntity.getCtEndTime().getTime()
                            || contractsEntity.getCtRemindTime()==null){
                        status = STATUS.REMINDTIMEERROR;
                        return status;
                    }
                }
//                /*当不需要提醒时，如果提醒时间存在，则ERROR*/
//                else if (contractsEntity.getCtIsWarn()==0 && contractsEntity.getCtRemindTime()!=null){
//                    status = STATUS.REMINDTIMEERROR;
//                    return status;
//                }
                /*如果开始时间大于结束时间，则ERROR*/
                if(contractsEntity.getCtStartTime().getTime() > contractsEntity.getCtEndTime().getTime()){
                    status = STATUS.STARTTIMEERROR;
                    return status;
                }
            }
            else {
                status = STATUS.FAIL;
                return status;
            }
            if (status == STATUS.SUCCESS) {
                contractsEntity.setContractUTime(new Timestamp(System.currentTimeMillis()));
                if(cate.equals("3")){
                    ContractsEntity check = contractsRepository.findByContractID(contractsEntity.getContractId());
                    if(!cate.equals(check.getContractCate() + "")){
                        payLogService.deletePeriodByContractId(contractsEntity.getContractId());
                        for(int i = 0; i <contractsEntity.getCtPeriodNum(); i++){
                            PeriodEntity periodEntity = new PeriodEntity();
                            periodEntity.setContractId(contractsEntity.getContractId());
                            periodEntity.setPeriodCTime(new Timestamp(System.currentTimeMillis()));
                            periodEntity.setPeriodPaidTime(new Timestamp(System.currentTimeMillis()));
                            periodEntity.setPeriodIsWarn((short) 1);
                            periodEntity.setPeriodRemindTime(new Timestamp(System.currentTimeMillis()));
                            periodEntity.setPeriodMoney((double) 0);
                            payLogService.addPeriod(periodEntity);
                        }
                    }
                }
                contractsRepository.saveAndFlush(contractsEntity);
            }
        }
        return status;
    }

    @Override
    public String addByExcel(MultipartFile file) throws IOException, BiffException {
        String message = "";
        File fileTemp = new File("temp");
        FileOutputStream fileOutputStream = new FileOutputStream(fileTemp);
        BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream);
        outputStream.write(file.getBytes());
        Workbook workbook = Workbook.getWorkbook(fileTemp);
        Sheet sheet = workbook.getSheet(0);
        int rows = sheet.getRows();

        /* excel列顺序 */
        /* 合同编号 */
        /* 合同名称 */
        /* 提交合同者ID（根据名称获取ID） */
        /* 提交者所属部门ID（根据名称获取ID） */
        /* 合同开始时间（格式：1999-09-09 12:12:12） */
        /* 合同结束时间（格式：1999-09-09 12:12:12） */
        /* 合同提醒时间（格式：1999-09-09 12:12:12） */
        /* 合同是否提醒 */
        /* 合同分期付款期数 */

        for (int i = 1;i < rows; i++){
            Cell cell = null;
            ContractsEntity contractsEntity = new ContractsEntity();

            /* 合同ID及合同编号 */
            if ((cell = sheet.getCell(0, i)) != null && !StringUtils.isBlank(cell.getContents())) {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                int random = (int)(Math.random()*10000);
                contractsEntity.setContractId(sdf.format(new java.util.Date()) + random + "");

                ContractsEntity check = contractsRepository.findByContractSerial(cell.getContents());
                if(check != null){
                    message = "Sheet1第" + (i+1) + "行：" + check.getContractId() + "编号合同已存在";
                    return message;
                }
                contractsEntity.setContractSerial(cell.getContents());
            } else {
                message = "Sheet1第" + (i+1) + "行：合同编号不为空";
                return message;
            }
            /* 合同名称 */
            if ((cell = sheet.getCell(1, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                contractsEntity.setContractName(cell.getContents());
            } else {
                message = "Sheet1第" + (i+1) + "行：合同名称不为空";
                return message;
            }

            /* 提交合同者ID（根据名称获取ID） */
            if ((cell = sheet.getCell(2, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                String userName = cell.getContents();
                UserEntity userEntity = userService.findByUserName(userName);

                contractsEntity.setUserId(userEntity.getUserId());
            } else {
                message = "Sheet1第" + (i+1) + "行：提交合同者不为空";
                return message;
            }

            /* 提交者所属部门ID（根据名称获取ID） */
            if ((cell = sheet.getCell(3, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                String depName = cell.getContents();
                DepartmentEntity departmentEntity = departmentService.findByDepartmentName(depName);

                contractsEntity.setDeptId(departmentEntity.getDeptId());
            } else {
                message = "Sheet1第" + (i+1) + "行：提交者所属部门不为空";
                return message;
            }

            /* 合同状态 */
            contractsEntity.setContractStatus(Short.parseShort("1"));

            /* 合同类别 */
            contractsEntity.setContractCate(Short.parseShort("3"));

            /* 合同开始时间 */
            if ((cell = sheet.getCell(4, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                Timestamp timestamp = Timestamp.valueOf(str);
                contractsEntity.setCtStartTime(timestamp);
            } else {
                message = "Sheet1第" + (i+1) + "行合同起始时间不为空";
                return message;
            }

            /* 合同结束时间 */
            if ((cell = sheet.getCell(5, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                Timestamp timestamp = Timestamp.valueOf(str);
                contractsEntity.setCtEndTime(timestamp);
            } else {
                message = "Sheet1第" + (i+1) + "行合同结束时间不为空";
                return message;
            }

            /* 合同是否提醒及提醒时间 */
            if ((cell = sheet.getCell(7, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();

                if (str.equals("是")) {
                    contractsEntity.setCtIsWarn(Short.parseShort("1"));
                    cell = sheet.getCell(6, i);

                    str = cell.getContents();
                    Timestamp timestamp = Timestamp.valueOf(str);
                    contractsEntity.setCtRemindTime(timestamp);
                } else {
                    contractsEntity.setCtIsWarn(Short.parseShort("0"));
                }
            } else {
                message = "Sheet1第" + (i+1) + "行合同提醒时间不为空";
                return message;
            }

            /* 合同分期付款期数 */
            if ((cell = sheet.getCell(8, i)) != null && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();

                contractsEntity.setCtPeriodNum(Short.parseShort(str));
            } else {
                message = "Sheet1第" + (i+1) + "行：合同分期付款期数不为空";
                return message;
            }

            /* 合同创建时间（当前时间） */
            /* 例：1999-09-09 12:12:12 */
            Timestamp d = new Timestamp(System.currentTimeMillis());
            contractsEntity.setContractCTime(d);

            contractsRepository.saveAndFlush(contractsEntity);
        }
        message = payLogService.addByExcel(file);
        return message;
    }

    @Override
    public List<ContractsCustomEntity> findBySrRemindTime() {
        return contractsRepository.findBySrRemindTime();
    }

    @Override
    public List<ContractsCustomEntity> findByEaRemindTime() {
        return contractsRepository.findByEaRemindTime();
    }

    @Override
    public List<ContractsCustomEntity> findByCtRemindTime() {
        return contractsRepository.findByCtRemindTime();
    }
}
